<template>
  <div class="probe-form" style="margin-top: 10px">
    <!-- 上方选项 -->
    <el-form :model="probeInfo" label-width="120px" size="small">
      <el-row :gutter="20" style="margin-bottom: 20px; width: 100%">
        <el-col :span="8">
          <el-form-item label="探针名称">
            <el-input v-model="probeInfo.name" placeholder="请输入探针名称" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="探针版本">
            <span>{{ probeInfo.version }}<span v-if="newVersion"> → {{ newVersion }}</span></span>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="探针种类">
            <el-select v-model="probeInfo.type" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="(item, index) in parsedValues"
                :key="index"
                :label="'种类'+(index+1)"
                :value="index"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="text-align: left;">
          <el-button type="primary" @click="handleSubmit">生成探针模型</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 主体区域 -->
    <el-row :gutter="20">
      <!-- 左侧表单 -->
      <el-col :span="16">
        <el-form :model="probeInfo" :rules="rules" ref="probeForm" label-width="120px" size="small">
          <!-- 环境试验参数 -->
          <el-card header="环境试验参数" style="margin-bottom: 20px;">
            <el-row v-for="(row, rowIndex) in formRows" :key="rowIndex" :gutter="20">
              <el-col v-for="(item, colIndex) in row" :key="colIndex" :span="8">
                <el-form-item :label="item.label" :prop="item.model">
                  <component
                    :is="item.component"
                    v-model="probeInfo[item.model]"
                    v-bind="item.props"
                    @change="item.model === 'measuringPointDistribution' ? handleDistributionChange(probeInfo[item.model]) : null"
                  >
                    <!-- select options -->
                    <template v-if="item.options && item.component === 'el-select'">
                      <el-option
                        v-for="opt in item.options"
                        :key="opt.value"
                        :label="opt.label"
                        :value="opt.value"
                      />
                    </template>
                    <!-- radio options -->
                    <template v-if="item.options && item.component === 'el-radio-group'">
                      <el-radio-button
                        v-for="opt in item.options"
                        :key="opt.value"
                        :label="opt.value"
                      >
                        {{ opt.label }}
                      </el-radio-button>
                    </template>
                  </component>

                  <!-- 自定义数值 -->
                  <el-input-number
                    v-if="item.model === 'measuringPointDistribution' && probeInfo.measuringPointDistribution === 3"
                    v-model="probeInfo.customDistributionValue"
                    placeholder="请输入自定义数目"
                    :min="1"
                    style="margin-top: 10px;"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <!--元件参数-->
          <el-card header="元件参数">
            <el-row v-for="(group, groupIndex) in componentList" :key="groupIndex" :gutter="20">
              <el-col :span="24">
                <h4>{{ group.name }}</h4>
              </el-col>
              <el-col v-for="(item, itemIndex) in group.items" :key="itemIndex" :span="6">
                <el-form-item :label="item.name" class="form-item-with-unit">
                  <div class="form-item-container">
                    <component :is="item.component" v-model="item.value" v-bind="item.props"
                    >
                      <!--下拉框-->
                      <template v-if="item.options">
                        <el-option
                          v-for="(option, optionIndex) in item.options"
                          :key="optionIndex"
                          :label="option.name"
                          :value="option.value"
                        />
                      </template>
                    </component>
                    <template v-if="item.unit">
                      <span class="unit">{{ item.unit }}</span>
                    </template>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="componentList.length === 0"><p>请选择一个探针种类以查看详细信息。</p></div>
          </el-card>
        </el-form>
      </el-col>

      <!-- 右侧视图区域 -->
      <el-col :span="8">
        <div class="view-panel">
          <h3>视图</h3>
          <div class="preview" style="margin-bottom: 20px;">总探针预览图</div>
          <div class="single-preview">单原件预览图</div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>


<script>
import {
  listProbeVariableParameter,
  getProbeVariableParameter,
  addProbeVariableParameter,
  updateProbeVariableParameter,
  getParameterTemplate,
} from "@/api/system/probeVariableParameter";
import {
  listProbeInfo,
  getProbeInfo,
  addProbeInfo,
  updateProbeInfo,
  delProbeInfo,
  getTemplateProbeIds
} from '@/api/system/probeInfo';
import { addProbeSignatureProcess } from '@/api/system/probeSignatureProcess';
import moment from 'moment';
import {getUserProfile} from "@/api/system/user";
import { getNewVersion } from "@/api/system/probeChangeRequest"
export default {
  data() {
    return {
      action: false, // 操作
      newVersion: null, // 新版本号
      probeInfo: {
        id: null, // 固定参数ID
        projectId: null, // 项目ID
        createdBy: null, // 创建人
        createdTime: null, // 创建时间
        updatedBy: null, // 更新人
        updatedTime: null, // 更新时间
        type: null, // 探针类型
        name: null, // 探针名称
        totalPressuer: null, // 总压
        totalTemperature: null, // 总温
        maxMach: null, // 最大马赫数
        strutStrength: null, // 支杆强度 (MPa)
        engineRpm: null, // 发动机转数
        measuringMedium: null, // 测量介质 (如空气、燃油)
        staticPressurePoints: null, // 静压测点数
        totalPressurePoints: null, // 总压测点数
        measuringPointDistribution: "uniform", // 测点分布 (如均匀分布)，默认为等距
        pressureInterfaceType: null, // 压力接口形式 (如螺纹)
        leadWireConfig: null, // 引线形式 (如屏蔽双绞线)
        flowPathDimension: null, // 流道尺寸 (如Φ200mm)
        version: null, // 版本号
        signatureStatus: null, // 签核状态(设计中，校对中审定中,被驳回)
        bomUrl: null, // BOM表URL
        drawingTwoUrl: null, // 2D图纸URL
        template: 0,// 不为模板
        delFlag: '0', //软删除标记
      },
      formRows: [
        [
          { label: "总温 (℃)", model: "totalTemperature", component: "el-input-number", props: { min: 0 } },
          { label: "总压 (Kpa)", model: "totalPressuer", component: "el-input-number", props: { min: 0 } },
          { label: "最大马赫数", model: "maxMach", component: "el-input-number", props: { min: 0 } },
        ],
        [
          { label: "支杆强度 (MPa)", model: "strutStrength", component: "el-input-number", props: { min: 0 } },
          { label: "发动机转数", model: "engineRpm", component: "el-input-number", props: { min: 0 } },
          {
            label: "测量介质",
            model: "measuringMedium",
            component: "el-select",
            options: [
              { label: "空气", value: "1" },
              { label: "燃油", value: "2" },
            ],
          },
        ],
        [
          { label: "静压测点数", model: "staticPressurePoints", component: "el-input-number", props: { min: 0 } },
          { label: "总压测点数", model: "totalPressurePoints", component: "el-input-number", props: { min: 0 } },
          {
            label: "测点分布",
            model: "measuringPointDistribution",
            component: "el-radio-group",
            options: [
              { label: "等距", value: "1" },
              { label: "等环", value: "2" },
              { label: "自定义", value: "3" },
            ],
          },
        ],
        [
          {
            label: "压力接口形式",
            model: "pressureInterfaceType",
            component: "el-select",
            options: [
              { label: "螺纹", value: "1" },
              { label: "法兰", value: "2" },
            ],
          },
          {
            label: "引线形式",
            model: "leadWireConfig",
            component: "el-select",
            options: [
              { label: "屏蔽双绞线", value: "1" },
              { label: "单线", value: "2" },
            ],
          },
          { label: "流道尺寸", model: "flowPathDimension", component: "el-input" },
        ],
      ],
      logUserId: null, // 当前登录用户ID
      componentList: [], // 元件种类列表
      parsedValues: [], // 解析后的元件参数
      templateProbeIds:[],// 模板探针ID
      rules: {
        name: [{ required: true, message: '探针名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '请选择探针种类', trigger: 'change' }],
        totalTemperature: [{ required: true, message: '请输入总温', trigger: 'blur' }],
        totalPressuer: [{ required: true, message: '请输入总压', trigger: 'blur' }],
        maxMach: [{ required: true, message: '请输入最大马赫数', trigger: 'blur' }],
        strutStrength: [{ required: true, message: '请输入支杆强度', trigger: 'blur' }],
        engineRpm: [{ required: true, message: '请输入发动机转数', trigger: 'blur' }],
        measuringMedium: [{ required: true, message: '请选择测量介质', trigger: 'change' }],
        staticPressurePoints: [{ required: true, message: '请输入静压测点数', trigger: 'blur' }],
        totalPressurePoints: [{ required: true, message: '请输入总压测点数', trigger: 'blur' }],
        measuringPointDistribution: [{ required: true, message: '请选择测点分布', trigger: 'change' }],
        pressureInterfaceType: [{ required: true, message: '请选择压力接口形式', trigger: 'change' }],
        leadWireConfig: [{ required: true, message: '请选择引线形式', trigger: 'change' }],
        flowPathDimension: [{ required: true, message: '请输入流道尺寸', trigger: 'blur' }],
      },
      variableId: null, // 元件参数id
    };
  },
  async created() {
    getUserProfile().then(response => {
      console.log('当前登录用户信息', response);
      this.logUserId = response.data.userId;
    });
    // 加载模板数据，生成 parsedValues
    await this.getTemplateProbeIds();
    console.log('当前探针模板',this.parsedValues)
    this.action = this.$route.query.action;

    // 新建探针、修改探针（nowVersion不变更版本）、修改探针(小版本变更)、版本变更
    if(this.action === 'create'){
      // 新建探针
      this.probeInfo.createdBy = this.$route.query.designerId; //
      this.probeInfo.projectId = this.$route.query.projectId;
      this.probeInfo.version = "1.0";
      console.log('当前登录用户id', this.probeInfo.createdBy);
      console.log('当前项目id', this.probeInfo.projectId);
    } else if (this.action === 'modify' || this.action === 'newVersion' || this.action === 'nowVersion') {
      // 修改探针
      this.probeInfo.id = this.$route.query.id;
      console.log('当前探针id',this.probeInfo.id)
      // 加载 probeInfo
      const res = await getProbeInfo(this.probeInfo.id);
      this.probeInfo = res.data;
      console.log('根据tanzhenid获取探针',res)
      // 类型转换
      this.probeInfo.type = Number(this.probeInfo.type);
      this.probeInfo.measuringMedium = Number(this.probeInfo.measuringMedium);
      this.probeInfo.measuringPointDistribution = Number(this.probeInfo.measuringPointDistribution);
      console.log('当前探针信息', this.probeInfo);
      // 暂时无法处理
      // 3. 加载原件参数模板（这个 JSON 是组件配置项）
      console.log('再一次打印探针id',this.probeInfo.id);
      const paramRes = await getParameterTemplate(`ids=${this.probeInfo.id}`);
      console.log('当前探针的元件参数模板', paramRes);
      this.variableId = paramRes.data[0].id;
      const parsedData = paramRes.data.map(item => {
        const fixed = item.value;//.replace(/^"|"$/g, '').replace(/\\"/g, '"');
        return JSON.parse(fixed);
      });
      console.log('解析后的元件参数', parsedData);
      console.log('parsedData is array?',Array.isArray(parsedData))
      this.componentList = parsedData[0].reduce((result, section) => {
        const existingGroup = result.find(group => group.name === section.name);
        const items = (section.items || section.data || []).map(item => ({
          name: item.name,
          model: `${section.name}_${item.name}`,
          component: 'el-input',
          props: { placeholder: `请输入 ${item.name}` },
          value: item.value,
          unit: item.unit
        }));
        if (existingGroup) {
          existingGroup.items.push(...items);
        } else {
          result.push({ name: section.name, items });
        }
        return result;
      }, []);
      console.log('当前探针的元件参数', this.componentList);
      console.log('长度',this.componentList.length)
      if(this.action === 'newVersion'|| this.action ==='modify') {
        // 获取新探针版本
        const versionRes = await getNewVersion((this.action==='modify'?'false':'true'),this.probeInfo.version);
        this.newVersion = versionRes.data;
        console.log('当前探针版本', this.probeInfo.version);
        console.log('新版本号', this.newVersion);
      }
    } else{
      this.$message('参数错误，请回上一界面')
    }
  },
  watch: {
    'probeInfo.type'(newVal) {
      if (newVal != null && this.parsedValues[newVal]) {
        this.generateComponentList(newVal);
      } else {
        this.componentList = [];
      }
    }
  },
  methods: {
    async getTemplateProbeIds() {
      try {
        const template = 1;
        const res = await getTemplateProbeIds(template);
        this.templateProbeIds = res.rows.map(item => item.id);
        const qs = this.templateProbeIds.map(id => `ids=${id}`).join('&');
        const paramRes = await getParameterTemplate(qs);
        console.log('元件参数模板', paramRes.data);
        console.log('第一个:', JSON.parse(paramRes.data[0].value));
        this.parsedValues = paramRes.data.map(item => {
          const fixed = item.value;//.replace(/^"|"$/g, '').replace(/\\"/g, '"');
          return JSON.parse(fixed);
        });
        console.log('解析后的元件参数parsedValues', this.parsedValues);
        console.log('当前探针的元件参数个数', this.parsedValues.length);
      } catch (error) {
        console.error('获取模板探针ID失败', error);
      }
    },
    generateComponentList(index) {
      const selectedData = this.parsedValues[index];
      console.log('当前探针的元件参数index', index);
      console.log('当前探针的元件参数', selectedData);
      this.componentList = selectedData.reduce((result, section) => {
        const existingGroup = result.find(group => group.name === section.name);
        const items = section.data.map(item => ({
          name: item.name,
          model: `${section.name}_${item.name}`,
          component: 'el-input',
          props: { placeholder: `请输入 ${item.name}` },
          value: item.value,
          unit: item.unit
        }));
        if (existingGroup) {
          existingGroup.items.push(...items);
        } else {
          result.push({ name: section.name, items });
        }
        return result;
      }, []);
      console.log('当前探针的元件参数componentList:', this.componentList);
    },
    handleDistributionChange(value) {
      if (value !== 3) {
        this.probeInfo.customDistributionValue = null;
      }
    },
    async handleSubmit() {
      this.$refs.probeForm.validate(async (valid) => {
        if (!valid) return;

        try {
          if (!this.componentList) {
            this.$message.error("探针种类或参数未选择");
            return;
          }
          if (this.probeInfo.projectId == null) {
            this.$message.warning("请返回项目详情页重新进入");
            return;
          }

          // 设置通用字段
          this.probeInfo.signatureStatus = '设计中';
          this.probeInfo.designerId = this.logUserId;

          let infoId = null;

          if (this.action === 'nowVersion') {
            // ✅ 当前版本修改，只更新探针和变量参数，不创建新探针、不提交签核
            await updateProbeInfo(this.probeInfo);
            infoId = this.probeInfo.id;

            const params = {
              id: this.variableId,
              infoId,
              value: JSON.stringify(this.componentList),
              template: 0
            };
            await updateProbeVariableParameter(params);

          } else {
            // ✅ create / modify / newVersion：创建新探针 + 新签核 + 新参数
            // 设置创建人时间（无论新建或基于旧版本新建）
            this.probeInfo.createdBy = this.logUserId;
            this.probeInfo.createdTime = moment().format('YYYY-MM-DD HH:mm:ss');

            // 设置版本号
            if (this.action === 'create') {
              this.probeInfo.version = '1.0';
            }
            if (this.action === 'modify' || this.action === 'newVersion') {
              // 若前端已赋值，则此处不修改；否则可以添加自动版本生成逻辑
              // this.probeInfo.version = yourVersionLogic();
              this.probeInfo.version = this.newVersion;
            }

            // 清除旧 ID，确保是新增
            const oldId = this.probeInfo.id;
            this.probeInfo.id = null;
            this.probeInfo.signatureStatus = "设计中";
            this.probeInfo.delFlag = '0';
            // 新增探针信息
            const res = await addProbeInfo(this.probeInfo);
            infoId = res.data.id;

            // 提交探针变量参数
            const params = {
              infoId,
              value: JSON.stringify(this.componentList),
              template: 0
            };
            await addProbeVariableParameter(params);

            // 提交签核流程
            const sigParams = {
              probeInfoId: infoId,
              createdBy: this.probeInfo.createdBy,
              createdTime: this.probeInfo.createdTime,
              stageName: "设计探针"
            };
            await addProbeSignatureProcess(sigParams);
          }

          this.$message.success("操作成功");
          // 操作成功后等待一秒返回上一级页面
          setTimeout(() => {
            // 关闭当前tabs
            this.$store.dispatch("tagsView/delView", this.$route);
            // 跳转路由
            this.$router.replace({
              name: "ProbeProjectDetail",
              query: {
                id: this.probeInfo.projectId
              }
            });
          }, 1000);
        } catch (err) {
          console.error("提交失败", err);
          this.$message.error("提交失败，请检查控制台");
        }
      });
    }
  }
};
</script>


<style scoped>
.view-panel {
  border: 1px solid #ebeef5;
  padding: 15px;
  border-radius: 4px;
  background-color: #fff;
}
.preview,
.single-preview {
  border: 1px dashed #ccc;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #999;
}
.distribution-container {
  display: flex;
  align-items: center;
}
.input-container {
  margin-left: 10px;
}
.form-item-with-unit .form-item-container {
  display: flex;
  align-items: center;
}

.form-item-with-unit .unit {
  margin-left: 8px; /* 调整间距 */
  white-space: nowrap; /* 防止换行 */
}
</style>
